package com.poisonh.unifiedauth.ui;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.fingerprint.FingerprintManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.lzy.okhttputils.model.HttpParams;
import com.poisonh.unifiedauth.R;
import com.poisonh.unifiedauth.dao.UserinfoDao;
import com.poisonh.unifiedauth.dao.UserinfoDaoImpl;
import com.poisonh.unifiedauth.model.UserInfoModel;
import com.poisonh.unifiedauth.ui.svprogresshud.SVProgressHUD;
import com.poisonh.unifiedauth.utils.ActivityStack;
import com.poisonh.unifiedauth.utils.ConstantUitls;
import com.poisonh.unifiedauth.utils.MyHttpsUtils;
import com.poisonh.unifiedauth.utils.PhoneUtils;
import com.poisonh.unifiedauth.utils.PreferencesUtils;
import com.poisonh.unifiedauth.utils.TimeUtils;
import com.poisonh.unifiedauth.utils.ToastUtils;
import com.poisonh.unifiedauth.utils.Utils;
import com.poisonh.unifiedauth.utils.aes.Base64Encoder;
import com.poisonh.unifiedauth.widget.pinview.IndicatorDots;
import com.poisonh.unifiedauth.widget.pinview.KeyboardView;
import com.poisonh.unifiedauth.widget.pinview.OnPasswordInputFinish;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Date;
import java.util.List;

import wish30.sm.sm;

/**
 * 密码设置界面
 * Created by PoisonH on 2016/7/1.
 * <p/>
 * 注：本文提到的PIN码与密码是同一个意思
 */
public class SettingPinCodeActivity extends AppCompatActivity implements View.OnClickListener, OnPasswordInputFinish
{
    private IndicatorDots mSettingPincodeDots;
    private KeyboardView mKeyboardView;
    private TextView mTvChangeAccount;
    private TextView mTvForgetPinCode;
    private TextView mTvSettingPinCodeTips;
    private ImageView mIvBack;
    private String mStrPinCode;
    private static int times = 0;
    //0注册，1更换PIN码,2忘记PIN码
    private static int modify = 0;

    private String mStrPk;//公钥
//    private String mStrSk;//私钥
    private byte[] mByteSk;//私钥
    private String mStrSkHash;//私钥Hash
    private String mStrSKSM4;//私钥SM4
    private String mSignature;//签名
    private String mStrPhone;//手机号

    //保存数据库
    private UserInfoModel model;

    private String mStrIdA;
    private String token;

    FingerDialogFragment mFragment;
    FingerprintManager mFingerprintManager;
    private final int FINTERPRINT_REQ_CODE = 1000;
    private static final String DIALOG_FRAGMENT_TAG = "myFragment";
    Date dt= new Date();
//    Long time1;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        ActivityStack.getAppManager().addActivity(this);
        mStrPhone = PreferencesUtils.getString(this, "PHONE");
        mStrIdA = PreferencesUtils.getString(this, "ID");
        setContentView(R.layout.activity_settingpincode);
        initView();


        if(ConstantUitls.TYPE == 0){
            mTvSettingPinCodeTips.setText("请设置密码");
        }
        if (ConstantUitls.TYPE == 1)
        {
            //登录，当用户登录的时候，判断本地是否存在用户数据，如果不存在，则向服务器获取数据
            checkData();
        }
        if (ConstantUitls.TYPE == 2)
        {
            //忘记PIN码
            mTvSettingPinCodeTips.setText(R.string.input_new_pincode_tips);
            mTvForgetPinCode.setVisibility(View.GONE);
            mTvChangeAccount.setVisibility(View.GONE);
            modify = 2;
        } else if (ConstantUitls.TYPE == 3)
        {
            //更换PIN码
            modify = 1;
            mIvBack.setVisibility(View.VISIBLE);
            mTvSettingPinCodeTips.setText(R.string.input_original_pincode_tips);
            mTvForgetPinCode.setVisibility(View.GONE);
            mTvChangeAccount.setVisibility(View.GONE);
        }else if(ConstantUitls.TYPE == 4 || ConstantUitls.TYPE == 5){
            int currentapiVersion = android.os.Build.VERSION.SDK_INT;
            if(currentapiVersion >= 23) {
                //指纹认证
                mFingerprintManager = (FingerprintManager) getSystemService(FINGERPRINT_SERVICE);
                //检查指纹识别器的权限
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        if (shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                            Toast.makeText(this, "没有使用指纹识别器的权限",Toast.LENGTH_LONG).show();
                        }
                        requestPermissions(new String[]{Manifest.permission.USE_FINGERPRINT}, FINTERPRINT_REQ_CODE);
                    }
                    return;
                }
                //如果没有提前设置指纹,则将购买按钮disable
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    // 判断硬件是否支持
                    if (!mFingerprintManager.isHardwareDetected()) {
                      //  Toast.makeText(this, "抱歉!本手机无指纹识别功能",Toast.LENGTH_SHORT).show();
                        return;
                    }
                    // 判断是否有已经录入的指纹
                    if(!mFingerprintManager.hasEnrolledFingerprints()){
                        Toast.makeText(this, "请在'设置 -> 安全 -> 指纹'中注册至少一个指纹",Toast.LENGTH_LONG).show();
                        return;
                    }
                }

                mFragment = FingerDialogFragment.newInstance();

               mFragment.show(getFragmentManager(), DIALOG_FRAGMENT_TAG);
            }
        }
    }


    private void initView()
    {
        mSettingPincodeDots = (IndicatorDots) findViewById(R.id.id_settingpincode_dots);
        mTvForgetPinCode = (TextView) findViewById(R.id.tv_forget_pincode);
        mTvChangeAccount = (TextView) findViewById(R.id.tv_change_account);
        mTvSettingPinCodeTips = (TextView) findViewById(R.id.tv_settingpincode_tips);
        mIvBack = (ImageView) findViewById(R.id.iv_back);
        mIvBack.setOnClickListener(this);
        mTvForgetPinCode.setOnClickListener(this);
        mTvChangeAccount.setOnClickListener(this);
        mKeyboardView = (KeyboardView) findViewById(R.id.virtualKeyboardView);
        mKeyboardView.setFinish(this);

    }

/*    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String[] permissions,
                                           int[] grantResults) {
        super.onRequestPermissionsResult(requestCode,
                permissions, grantResults);
        if (requestCode == FINTERPRINT_REQ_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                purchaseButton.setEnabled(true);
            }
        }
    }*/

    @Override
    public void inputChange(int length)
    {
        mSettingPincodeDots.updateDot(length);
    }

    @Override
    public void inputFinish(final String pin)
    {
        mSettingPincodeDots.updateDot(pin.length());
        SVProgressHUD.showWithStatus(SettingPinCodeActivity.this, "加载中...");
        //延迟200毫秒，解决输入卡顿问题
        new Handler().postDelayed(new Runnable()
        {
            @Override
            public void run()
            {
                businessLogic(pin);
            }
        }, 100);

//        businessLogic(pin);
    }


    /**
     * 业务逻辑处理
     *
     * @param pin
     */
    private void businessLogic(String pin)
    {
        if ((ConstantUitls.TYPE == 4 || ConstantUitls.TYPE == 5) && pin.length() == 6)
        {
            mStrPinCode = pin;
            haveTokenLogin();
        }
        //登录
        else if (ConstantUitls.TYPE == 1 && pin.length() == 6)
        {
            mStrPinCode = pin;
//            time1 = System.currentTimeMillis();
            login();
        }
        //更改PIN码
        else if (ConstantUitls.TYPE == 3 && pin.length() == 6)
        {
            //判断与原PIN码的hash是否相等
            if (equalPinCode(pin))
            {

                mTvSettingPinCodeTips.setText(R.string.input_new_pincode_tips);
                mKeyboardView.cleanLength();
                mSettingPincodeDots.updateDot(0);
                ConstantUitls.TYPE = 0;
                modify = 1;
                SVProgressHUD.dismiss(SettingPinCodeActivity.this);
                return;
            } else
            {
                SVProgressHUD.dismiss(SettingPinCodeActivity.this);
                mKeyboardView.cleanLength();
                mSettingPincodeDots.updateDot(0);
                ToastUtils.showToast(SettingPinCodeActivity.this, "密码输入错误,请重新输入");
            }
        }
        //注册或者忘记PIN码
        else if ((ConstantUitls.TYPE == 0 || ConstantUitls.TYPE == 2) && pin.length() == 6)
        {
            if (pin.length() == 6 && times == 0)
            {
                mStrPinCode = pin;
                times++;
                mTvSettingPinCodeTips.setText(R.string.settingpincode_agin_tips);
                mKeyboardView.cleanLength();
                mSettingPincodeDots.updateDot(0);
                SVProgressHUD.dismiss(SettingPinCodeActivity.this);
                return;
            }
            if (pin.length() == 6 && times == 1)
            {
                if (!pin.equals(mStrPinCode))
                {
                    ToastUtils.showToast(SettingPinCodeActivity.this, "两次密码不一致");
                    times = 0;
                    mStrPinCode = "";
                    mTvSettingPinCodeTips.setText(R.string.input_new_pincode_tips);
                    mKeyboardView.cleanLength();
                    mSettingPincodeDots.updateDot(0);
                    SVProgressHUD.dismiss(SettingPinCodeActivity.this);
                } else
                {
                    if (modify == 0)
                    {
                        //注册
                        registry(pin);
                    } else if (modify == 1)
                    {
                        //修改PIN码
                        modifyPin(pin);
                    } else if (modify == 2)
                    {
                        //忘记PIN码，更新用户PIN码
                        updateUserKey(pin);
                    }
                }
            }
        }
    }

    /**
     * 当本地存在token时，登录逻辑
     */
    private void haveTokenLogin()
    {
        byte[] mByteNewSk = null;
        try
        {
            UserinfoDaoImpl mUserinfoDaoImpl = new UserinfoDaoImpl(SettingPinCodeActivity.this);
            List<UserInfoModel> model = mUserinfoDaoImpl.queryReturnList(mStrIdA);
            //mStrNewSk = AESUtils.decrypt(model.get(0).getmStringConfSK(), RSAUtils.encryptBASE64(MD5Utils.getMD5String(mStrPinCode)).trim());
            //mStrNewSk = IosAndJavaAES.decode(Utils.encryptBASE64(MD5Utils.getMD5String(mStrPinCode)).trim(), model.get(0).getmStringConfSK());
            mByteNewSk = sm.getInstance().sm4CbcDecrypt(Utils.decryptBASE64(model.get(0).getmStringConfSK()), 32, sm.getInstance().sm3(mStrPinCode.getBytes(), mStrPinCode.getBytes().length));
        } catch (Exception e)
        {
            e.printStackTrace();
        } finally
        {
            //解密成功之后再次用解密出来的sk与PIN码的hash进行加密，然后与原AES私钥进行对比。
            if (mByteNewSk != null)
            {
                if (!checkPinCode(mByteNewSk))
                {
                    ToastUtils.showToast(SettingPinCodeActivity.this, "密码错误");
                    times = 0;
                    mStrPinCode = "";
                    mKeyboardView.cleanLength();
                    mSettingPincodeDots.updateDot(0);
                    mTvSettingPinCodeTips.setText("请重新输入您的密码");
                    SVProgressHUD.dismiss(SettingPinCodeActivity.this);
                    return;
                } else
                {
                    try
                    {
                        if (ConstantUitls.TYPE == 4)
                        {
                            Base64Encoder.encode(sm.getInstance().sm3(mStrPinCode.getBytes(), mStrPinCode.getBytes().length));
                            Intent mIntent = new Intent(SettingPinCodeActivity.this, MainActivity.class);
                            mIntent.putExtra("PHONE", mStrPhone);
                            startActivity(mIntent);
                            overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                            finish();
                            SVProgressHUD.dismiss(SettingPinCodeActivity.this);
                        } else if (ConstantUitls.TYPE == 5)
                        {
                            finish();
                        }
                    } catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }
            }
            //如果未解出，则PIN码输入错误
            if (mByteNewSk == null)
            {
                ToastUtils.showToast(SettingPinCodeActivity.this, "密码错误");
                times = 0;
                mStrPinCode = "";
                mKeyboardView.cleanLength();
                mSettingPincodeDots.updateDot(0);
                mTvSettingPinCodeTips.setText("请重新输入您的密码");
                SVProgressHUD.dismiss(SettingPinCodeActivity.this);
                //  mSettingPincodeView.resetPinLockView();
                return;
            }
        }
    }


    @Override
    public void onClick(View v)
    {
        switch (v.getId())
        {
            case R.id.tv_forget_pincode:
                //  ConstantUitls.mStrPhone = mStrPhone;
                startActivity(new Intent(SettingPinCodeActivity.this, FindPassWd.class));
                break;
            case R.id.tv_change_account:
                startActivity(new Intent(SettingPinCodeActivity.this, LoginActivity.class));
                ConstantUitls.TYPE = 1;
                //将视频审核状态改为false，防止用户切换账号，请求不到用户视频审核状态。
                PreferencesUtils.putBoolean(SettingPinCodeActivity.this, "VideoState", false);
                PreferencesUtils.deleteValue(SettingPinCodeActivity.this, "ID");
                ActivityStack.getAppManager().exit();
                finish();
                break;
            case R.id.iv_back:
                finish();
                break;
        }
    }

    /**
     * 注册
     *
     * @param pin
     */
    private void registry(String pin)
    {
        try
        {
            HttpParams params = getHttpsParams(pin, false);

            MyHttpsUtils.post(ConstantUitls.REQUEDT_URL + ConstantUitls.REGISTRY, params, new MyHttpsUtils.ResultCallback()
            {
                @Override
                public void onSuccess(String response)
                {
                    Log.d("SettingPinCodeActivity", response);
                    try
                    {
                        JSONObject object = new JSONObject(response);
                        JSONObject object1 = new JSONObject(object.getString("results"));
                        mStrIdA = object1.getString("userId");

                        model = new UserInfoModel();
                        model.setId(mStrIdA);
                        model.setmStrPhone(mStrPhone);
                        model.setmStringHashSk(mStrSkHash);
                        model.setmStringConfSK(mStrSKSM4);
                        saveData(model);

                        // ConstantUitls.mStrId = mStrId;
                        UserinfoDaoImpl mUserinfoDaoImpl = new UserinfoDaoImpl(SettingPinCodeActivity.this);
                        List<UserInfoModel> model = mUserinfoDaoImpl.queryReturnList(mStrIdA);
                        if (model.size() != 0)
                        {
                            login();
                        }

                    } catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(String failReason)
                {
                    ToastUtils.showToast(SettingPinCodeActivity.this, "注册失败");
                    //注册失败时，清空密码框。并且将输入次数，以及密码清空。
                    mKeyboardView.cleanLength();
                    mSettingPincodeDots.updateDot(0);
                    times = 0;
                    mStrPinCode = "";
                    modify = 0;
                    PreferencesUtils.deleteValue(SettingPinCodeActivity.this, "ID");
                }
            });
        } catch (Exception e)
        {
            e.printStackTrace();
        }

    }

    /**
     * 修改PIN码
     *
     * @param pin
     */
    private void modifyPin(String pin)
    {
        try
        {
            HttpParams params = getHttpsParams(pin, true);

            MyHttpsUtils.post(ConstantUitls.REQUEDT_URL + ConstantUitls.MODIFYPIN, params, new MyHttpsUtils.ResultCallback()
            {
                @Override
                public void onSuccess(String response)
                {
                    Log.d("SettingPinCodeActivity", response);
                    try
                    {
                        //将数据存储到数据库
                        saveDatabase();

                        login();
                        times = 0;
                    } catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(String failReason)
                {
                    ToastUtils.showToast(SettingPinCodeActivity.this, "修改密码失败");
                    //修改密码失败时，清空密码框。并且将输入次数，以及密码清空。
                    mKeyboardView.cleanLength();
                    mSettingPincodeDots.updateDot(0);
                    times = 0;
                    mStrPinCode = "";
                    modify = 1;
                }
            });
        } catch (Exception e)
        {
            e.printStackTrace();
        }

    }

    /**
     * 登录
     */

    private void login()
    {
        HttpParams params = new HttpParams();
        try
        {
            UserinfoDaoImpl mUserinfoDaoImpl = new UserinfoDaoImpl(SettingPinCodeActivity.this);
            List<UserInfoModel> model = mUserinfoDaoImpl.queryReturnList(mStrIdA);
            //判断本地是否有个人用户信息，如果没有，则请求服务器获取。
            if (model.size() == 0)
            {
                getUserinfo();
                try
                {
                    // mStrSk = AESUtils.decrypt(model.get(0).getmStringConfSK(), RSAUtils.encryptBASE64(MD5Utils.getMD5String(mStrPinCode)).trim());
                    //mStrSk = IosAndJavaAES.decode(Utils.encryptBASE64(MD5Utils.getMD5String(mStrPinCode)).trim(), model.get(0).getmStringConfSK());
                    mByteSk = sm.getInstance().sm4CbcDecrypt(Utils.decryptBASE64(model.get(0).getmStringConfSK()), 32, sm.getInstance().sm3(mStrPinCode.getBytes(), mStrPinCode.getBytes().length));
                } catch (Exception e)
                {
                    e.printStackTrace();
                } finally
                {
                    if (mByteSk == null)
                    {
                        ToastUtils.showToast(SettingPinCodeActivity.this, "密码错误");
                        times = 0;
                        mStrPinCode = "";
                        mKeyboardView.cleanLength();
                        mSettingPincodeDots.updateDot(0);
                        mTvSettingPinCodeTips.setText("请重新输入您的密码");
                        SVProgressHUD.dismiss(SettingPinCodeActivity.this);
                        //  mSettingPincodeView.resetPinLockView();
                        return;
                    }
                    //签名
                    //mSignature = RSAUtils.sign(mStrPhone.getBytes(), mStrSk);
                    mSignature = Utils.encryptBASE64(sm.getInstance().sm2Signature(mStrPhone.getBytes(), mStrPhone.getBytes().length, mByteSk));
                }
            } else
            {
                try
                {
                    //解密，通过用户输入的PIN码与原AES密钥进行解密
                    //  mStrSk = Cryptogram.decrypt(RSAUtils.encryptBASE64(MD5Utils.getMD5String(mStrPinCode)), model.get(0).getmStringConfSK());
                    //mStrSk= AESUtils.decrypt(model.get(0).getmStringConfSK().getBytes(),RSAUtils.encryptBASE64(MD5Utils.getMD5String(mStrPinCode))).toString();
                    // mStrSk = AESUtils.decrypt(model.get(0).getmStringConfSK(), RSAUtils.encryptBASE64(MD5Utils.getMD5String(mStrPinCode)).trim());
                    //mStrSk = IosAndJavaAES.decode(Utils.encryptBASE64(MD5Utils.getMD5String(mStrPinCode)).trim(), model.get(0).getmStringConfSK());
                    mByteSk = sm.getInstance().sm4CbcDecrypt(Utils.decryptBASE64(model.get(0).getmStringConfSK()), 32, sm.getInstance().sm3(mStrPinCode.getBytes(), mStrPinCode.getBytes().length));
                } catch (Exception e)
                {
                    mByteSk = null;
                    e.printStackTrace();
                } finally
                {
                    //解密成功之后再次用解密出来的sk与PIN码的hash进行加密，然后与原AES私钥进行对比。
                    if (mByteSk != null)
                    {
                        if (!checkPinCode(mByteSk))
                        {
                            ToastUtils.showToast(SettingPinCodeActivity.this, "密码错误");
                            times = 0;
                            mStrPinCode = "";
                            mKeyboardView.cleanLength();
                            mSettingPincodeDots.updateDot(0);
                            mTvSettingPinCodeTips.setText("请重新输入您的密码");
                            SVProgressHUD.dismiss(SettingPinCodeActivity.this);
                            //  mSettingPincodeView.resetPinLockView();
                            return;
                        }
                    }
                    //如果未解出，则PIN码输入错误
                    if (mByteSk == null)
                    {
                        ToastUtils.showToast(SettingPinCodeActivity.this, "密码错误");
                        times = 0;
                        mStrPinCode = "";
                        mKeyboardView.cleanLength();
                        mSettingPincodeDots.updateDot(0);
                        mTvSettingPinCodeTips.setText("请重新输入您的密码");
                        SVProgressHUD.dismiss(SettingPinCodeActivity.this);
                        //  mSettingPincodeView.resetPinLockView();
                        return;
                    }
                    //签名
                    mSignature = Utils.encryptBASE64(sm.getInstance().sm2Signature(mStrPhone.getBytes(), mStrPhone.getBytes().length, mByteSk));
                }
            }
            params.put("APIVersion", PhoneUtils.getAPIVersion());
            params.put("equiModel", PhoneUtils.getPhoneModel());
            params.put("equiVersion", PhoneUtils.getPhoneVersion());
            params.put("signature", mSignature);
            params.put("equiType", "1");
            params.put("phone", mStrPhone);

        } catch (Exception e)
        {
            e.printStackTrace();
        }
        String url = "";
        if (ConstantUitls.TYPE == 0 || ConstantUitls.TYPE == 1)
        {
            //
            url = ConstantUitls.REQUEDT_URL + ConstantUitls.LOGIN;
        }
        MyHttpsUtils.post(url, params, new MyHttpsUtils.ResultCallback()
        {
            @Override
            public void onSuccess(String response)
            {
                try
                {
                    if (saveInfo(response))
                    {
                        if (modify == 1)
                        {
                            ActivityStack.getAppManager().exit();
                        }
                        SVProgressHUD.dismiss(SettingPinCodeActivity.this);

                        if (ConstantUitls.TYPE == 0 && modify == 0) {
                            //Intent setHeadIntent = new Intent(SettingPinCodeActivity.this, SettingCardActivity.class);// 注册流程增加头像
                           // setHeadIntent.putExtra("code", "1");
                          //  setHeadIntent.putExtra("PHONE", mStrPhone);
                            //startActivity(setHeadIntent);
                            //Log.e("timeTest",String.valueOf(System.currentTimeMillis() - time1));
                            Intent mIntent = new Intent(SettingPinCodeActivity.this, MainActivity.class);
                            mIntent.putExtra("PHONE", mStrPhone);
                            startActivity(mIntent);

                        } else {
                           // Log.e("timeTest",String.valueOf(System.currentTimeMillis() - time1));
                            Intent mIntent = new Intent(SettingPinCodeActivity.this, MainActivity.class);
                            mIntent.putExtra("PHONE", mStrPhone);
                            startActivity(mIntent);
                        }
                        overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                        finish();
                    }
                } catch (Exception e)
                {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(String failReason)
            {
                ToastUtils.showToast(SettingPinCodeActivity.this, "登录失败");
                //注册失败时，清空密码框。并且将输入次数，以及密码清空。
                mKeyboardView.cleanLength();
                mSettingPincodeDots.updateDot(0);
                mStrPinCode = "";
                SVProgressHUD.dismiss(SettingPinCodeActivity.this);
            }
        });
    }


    /**
     * 保存个人信息
     *
     * @param response
     */
    private boolean saveInfo(String response)
    {
        try
        {

            //根据id查询用户
            UserinfoDaoImpl mUserinfoDaoImpl = new UserinfoDaoImpl(SettingPinCodeActivity.this);
            UserInfoModel model = mUserinfoDaoImpl.queryReturnOne(mStrIdA);

            JSONObject object = new JSONObject(response);
            JSONObject object1 = new JSONObject(object.getString("results"));
            token = object1.getString("token");
            mStrIdA = object1.getString("id");
            //  ConstantUitls.mStrId = object1.getString("id");
            String mStrPhone = object1.getString("phone");
            String name = object1.getString("name");
            if (!name.equals("null"))
            {
                model.setmStrUserName(name);
            }
            String email = object1.getString("email");

            if (!name.equals("null"))
            {
                model.setmStrUserEmail(email);
            }
            String mStrHeadUrl = ConstantUitls.REQUEDT_IMG_URL + object1.getString("headImg");

            //时间
            model.setmDeadDate(TimeUtils.getNowTime());
            //用户token
            model.setmStrToken(token);
            //用户信用分数
            model.setmStringScore(object1.getString("score"));
            //用户头像地址
            model.setmStrHeadUrl(mStrHeadUrl);
            model.setmStrPhone(mStrPhone);
            mUserinfoDaoImpl.commit();

            PreferencesUtils.putString(SettingPinCodeActivity.this, "ID", mStrIdA);

            return true;
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 用户忘记密钥服务
     *
     * @param pin
     */
    private void updateUserKey(String pin)
    {
        try
        {
            HttpParams params = getHttpsParams(pin, true);

            MyHttpsUtils.post(ConstantUitls.REQUEDT_URL + ConstantUitls.UPDATEUSERKEY, params, new MyHttpsUtils.ResultCallback()
            {
                @Override
                public void onSuccess(String response)
                {
                    saveDatabase();
                    ConstantUitls.TYPE = 1;
                    login();
                    times = 0;
                }

                @Override
                public void onFailure(String failReason)
                {
                    ToastUtils.showToast(SettingPinCodeActivity.this, failReason);
                }
            });

        } catch (Exception e)
        {
            e.printStackTrace();
        }

    }

    /**
     * 请求参数
     *
     * @param pin
     * @return
     * @throws Exception
     */
    private HttpParams getHttpsParams(String pin, boolean modify) throws Exception
    {
        HttpParams params = new HttpParams();
        byte[] publicKey = new byte[64];
        byte[] privateKey = new byte[32];
        try
        {
            byte[] sm2Key = sm.getInstance().sm2GenerateKeyPair();//2016.12.6 王迪 修改为商密算法
            for(int i=0;i<32;i++)
            {
                publicKey[i] = sm2Key[i];
                publicKey[32 + i] = sm2Key[32 + i];
                privateKey[i] = sm2Key[64 + i];
            }
            //获取公钥
            mStrPk = Utils.encryptBASE64(publicKey).trim();
            //获取私钥
            mByteSk = privateKey;
            //私钥Hash
            mStrSkHash = Utils.encryptBASE64(sm.getInstance().sm3(privateKey, privateKey.length)).trim();
            mStrSKSM4 = Utils.encryptBASE64(sm.getInstance().sm4CbcEncrypt(privateKey, 32, sm.getInstance().sm3(pin.getBytes(), pin.getBytes().length))).trim();
            //签名
            mSignature = Utils.encryptBASE64(sm.getInstance().sm2Signature(mStrPhone.getBytes(), mStrPhone.getBytes().length, privateKey)).trim();

            //公钥
            params.put("pk", mStrPk);
            //私钥hash
            params.put("originalSK", mStrSkHash);
            //私钥AES
            params.put("encryptSK", mStrSKSM4);
            //签名
            params.put("signature", mSignature);
            //手机号
            params.put("phone", mStrPhone);

            if (modify)
            {
                //  用户id
                // params.put("id", ConstantUitls.mStrId);
                params.put("id", mStrIdA);
                // 用户token
                params.put("token", getUserToekn());
            }

        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return params;
    }

    /**
     * 请求服务器，获取用户私钥信息
     */
    private void getUserinfo()
    {
        HttpParams params = new HttpParams();
        params.put("id", mStrIdA);
        MyHttpsUtils.post(ConstantUitls.REQUEDT_URL + ConstantUitls.GETUSERSKINFO, params, new MyHttpsUtils.ResultCallback()
        {
            @Override
            public void onSuccess(String response)
            {
                try
                {
                    JSONObject object = new JSONObject(response);
                    JSONObject data = object.getJSONObject("results");
                    //原私钥hash
                    mStrSkHash = data.getString("u_original");
                    //原私钥aes
                    mStrSKSM4 = data.getString("u_encrypt");

                    //  ConstantUitls.mStrId = mStrId;

                    model = new UserInfoModel();
                    model.setId(mStrIdA);
                    model.setmStrPhone(mStrPhone);
                    model.setmStringHashSk(mStrSkHash);
                    model.setmStringConfSK(mStrSKSM4);
                    saveData(model);

                } catch (JSONException e)
                {
                    e.printStackTrace();
                } catch (Exception e)
                {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(String failReason)
            {
                // SVProgressHUD.showWithStatus(SettingPinCodeActivity.this, false);
            }
        });
    }

    /**
     * 保存数据
     */
    private void saveData(UserInfoModel model)
    {
        try
        {
            UserinfoDaoImpl mUserinfoDaoImpl = new UserinfoDaoImpl(SettingPinCodeActivity.this);
            mUserinfoDaoImpl.addone(model);
        } catch (JSONException e)
        {
            e.printStackTrace();
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    /**
     * 存储数据库
     */
    private void saveDatabase()
    {

        try
        {
            UserinfoDaoImpl mUserinfoDaoImpl = new UserinfoDaoImpl(SettingPinCodeActivity.this);
            UserInfoModel model = mUserinfoDaoImpl.queryReturnOne(mStrIdA);
            model.setmDeadDate(TimeUtils.getNowTime());
            model.setmStrToken(token);
            model.setmStringConfSK(mStrSKSM4);
            model.setmStringHashSk(mStrSkHash);
            mUserinfoDaoImpl.commit();

        } catch (Exception e)
        {
            e.printStackTrace();
        }

    }

    /**
     * 判断用户输入的PIN码
     *
     * @param pin
     * @return
     */
    private boolean equalPinCode(String pin)
    {
        try
        {
            UserinfoDaoImpl mUserinfoDaoImpl = new UserinfoDaoImpl(SettingPinCodeActivity.this);
            //获取到数据库中保存的AES SK，然后使用解密算法进行解密
//            String mStrAESSK = mUserinfoDaoImpl.queryReturnList(ConstantUitls.mStrId).get(0).getmStringConfSK();
            String mStrSM4SK = mUserinfoDaoImpl.queryReturnList(mStrIdA).get(0).getmStringConfSK();
            //解密出SK的值
            // String mStrSK = Cryptogram.decrypt(RSAUtils.encryptBASE64(MD5Utils.getMD5String(pin)), mStrAESSK);
            //String mStrSK = AESUtils.decrypt(mStrAESSK, RSAUtils.encryptBASE64(MD5Utils.getMD5String(pin)).trim());
            byte[] mStrSK = sm.getInstance().sm4CbcDecrypt(Utils.decryptBASE64(mStrSM4SK), 32, sm.getInstance().sm3(pin.getBytes(), pin.getBytes().length));
            if (mStrSK == null)
            {
                return false;
            }
            if (mStrSK != null)
            {
                return checkPinCode(mStrSK);
            }

        } catch (Exception e)
        {
            e.printStackTrace();
        }

        return false;
    }

    /**
     * 判断是否与原PIN码一致
     *
     * @return
     */
    private boolean checkPinCode(byte[] sk)
    {
        String mStrNewSKHash = null;
        String mStrOldSKHash = null;
        //解密成功之后再次用解密出来的sk的hash，与原来的sk的hash对比。
        try
        {
            mStrNewSKHash = Utils.encryptBASE64(sm.getInstance().sm3(sk, 32)).trim();
            UserinfoDaoImpl mUserinfoDaoImpl = new UserinfoDaoImpl(SettingPinCodeActivity.this);
            //  List<UserInfoModel> model = mUserinfoDaoImpl.queryReturnList(ConstantUitls.mStrId);
            List<UserInfoModel> model = mUserinfoDaoImpl.queryReturnList(mStrIdA);
            if (model.size() != 0)
            {
                mStrOldSKHash = model.get(0).getmStringHashSk();
            }
            if (mStrOldSKHash.equals(mStrNewSKHash))
            {
                return true;
            }
        } catch (Exception e)
        {
            e.printStackTrace();
            return false;
        }
        return false;
    }

    /**
     * 当为登录状态时，首先判断本地是否有当前用户信息，没有则下载下来保存本地
     */
    private void checkData()
    {
        try
        {
            UserinfoDaoImpl mUserinfoDaoImpl = new UserinfoDaoImpl(SettingPinCodeActivity.this);
            List<UserInfoModel> model = mUserinfoDaoImpl.queryReturnList(mStrIdA);
            //判断本地是否有个人用户信息，如果没有，则请求服务器获取。
            if (model.size() == 0)
            {
                //发送服务器数据请求
                Message msg = Message.obtain();
                msg.what = 0;
                mActionHandler.sendMessage(msg);
            } else
            {
                //获取用户id
                //   ConstantUitls.mStrId = model.get(0).getId();
                mStrIdA = model.get(0).getId();
//                //获取用户token
//                token = model.get(0).getmStrToken();
//                //获取用户手机号码
//                mStrPhone = model.get(0).getmStrPhone();
            }
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    Handler mActionHandler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            super.handleMessage(msg);
            switch (msg.what)
            {
                case 0:
                    getUserinfo();
                    break;
                case 1:
                    //保存数据库
                    model = new UserInfoModel();
                    model.setId(mStrIdA);
                    model.setmStrPhone(mStrPhone);
                    model.setmStringHashSk(mStrSkHash);
                    model.setmStringConfSK(mStrSKSM4);
                    saveData(model);
                    break;
            }
        }
    };

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        ActivityStack.getAppManager().finishActivity(this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_BACK && ConstantUitls.TYPE == 5)
        {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 获取用户token
     *
     * @return
     */
    private String getUserToekn()
    {

        String mUserid = PreferencesUtils.getString(this, "ID");

        try
        {

            UserinfoDao mUserinfoDaoImpl = new UserinfoDaoImpl(getApplicationContext());
            List<UserInfoModel> model = mUserinfoDaoImpl.queryReturnList(mUserid);
            return model.get(0).getmStrToken();
        } catch (Exception e)
        {
            e.printStackTrace();
        }

        return null;
    }
}
